package cn.itsource.crm.service.impl;

import cn.itsource.crm.domain.DepositOrder;
import cn.itsource.crm.mapper.DepositOrderMapper;
import cn.itsource.crm.service.IDepositOrderService;
import cn.itsource.util.OddNumUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Map;

@Service
public class DepositOrderServiceImpl extends BaseServiceImpl<DepositOrder> implements IDepositOrderService {

    @Autowired
    private DepositOrderMapper depositOrderMapper;

    /**
     * 保存的时候自动生成定金单号
     * @param depositOrder
     */
    @Override
    public void save(DepositOrder depositOrder) {

        //通过工具类生成唯一单号
        String oddNum = OddNumUtil.getoddNum();
        //将单号设置到定金订单对象中
        depositOrder.setSn(oddNum);
        //保存到数据库
        super.save(depositOrder);
    }

    /**
     * 删除订单的时候，删除订单与合同的关联，中间表
     * @param id
     */
    @Override
    public void delete(Serializable id) {
        //删除中间表信息
        deleteOrderAndContract(id);
        //删除订单
        super.delete(id);
    }

    /**
     * 删除订单之前，通过订单id，删除与合同之间的关联信息
     * @param id
     */
    @Override
    public void deleteOrderAndContract(Serializable id) {
        depositOrderMapper.deleteOrderAndContract(id);
    }

    @Override
    public void batchDelete(Map map) {
        String str = (String) map.get("ids");
        if(StringUtils.isNotEmpty(str)){
            String[] strArray=str.split(",");

            int[] arr=new int[strArray.length];
            for(int i=0;i<strArray.length;i++){
                arr[i]=Integer.parseInt(strArray[i]);
            }

            //先批量删除中间表信息
            depositOrderMapper.batchDeleteMiddle(arr);
            //再批量删除订单
            depositOrderMapper.batchDelete(arr);
        }
    }
}
